<?php

/**
 * DB类 Yjnic_Db_Query
 *
 * @author prettyyjnic <prettyyjnic@qq.com> 20151027
 */
class Yjnic_Db_Query {

    protected $_pdo_ins = NULL;
    protected $_query_id = false;
    protected $_last_sql = '';

    public function __construct(PDO $pdo){
        $this->_pdo_ins = $pdo;
    }

    /**
     * fetchAll
     */
    public function fetchAll($sql, $params=array()){
        $this->_query_id = $this->_pdo_ins->prepare($sql);
        $this->_last_sql = $sql;
        $this->_query_id->execute($params);
        return $this->_query_id->fetchAll(PDO::FETCH_ASSOC);
    }

    /**
     * fetchRow
     */
    public function fetchRow($sql, $params=array()){
        if (strpos($sql, "LIMIT")===false) {
            $sql .= " LIMIT 1 ";
        }
        $ret = $this->fetchAll($sql, $params);
        if ($ret) {
            return array_shift($ret);
        }else{
            return array();
        }
    }

    /**
     * getAll,返回map
     */
    public function getAll($sql, $field, $params=array()){
        $data = $this->fetchAll($sql, $params);
        $ret = array();
        if ($data) {
            foreach ($data as $key => $value) {
                $ret[$value[$field]] = $value;
            }
        }
        
        return $ret;
    }

    /**
     * getRow 返回map
     */
    public function getRow($sql, $field, $params=array()){
        $data = $this->fetchRow($sql, $params);
        $ret = array();
        if ($data) {
            $ret[$data[$field]] = $data;        
        }    
        return $ret;
    }

    /**
     * getOne 返回一个值
     */
    public function getOne($sql, $params=array()){
        $data = $this->fetchRow($sql, $params);
        if ($data) {
            return array_shift($data);
        }else
            return array();
    }

    /**
     *  get last sql
     */
    public function getLastSql(){
        return $this->_last_sql;
    }

}